"""
环境管理API端点
"""
from typing import Any, List
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session

from app.core.database import get_db
from app.models.environment import Environment
from app.models.user import User
from app.schemas.environment import Environment as EnvironmentSchema, EnvironmentCreate, EnvironmentUpdate
from app.api.endpoints.auth import get_current_user

router = APIRouter()


@router.get("/", response_model=List[EnvironmentSchema])
async def get_environments(
    skip: int = 0,
    limit: int = 100,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
) -> Any:
    """获取环境列表"""
    environments = db.query(Environment).offset(skip).limit(limit).all()
    return environments


@router.get("/{env_id}", response_model=EnvironmentSchema)
async def get_environment(
    env_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
) -> Any:
    """获取环境详情"""
    environment = db.query(Environment).filter(Environment.id == env_id).first()
    if not environment:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="环境不存在"
        )
    return environment


@router.post("/", response_model=EnvironmentSchema)
async def create_environment(
    env_in: EnvironmentCreate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
) -> Any:
    """创建环境"""
    # 检查环境名是否已存在
    if db.query(Environment).filter(Environment.name == env_in.name).first():
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="环境名已存在"
        )
    
    # 创建环境
    environment = Environment(**env_in.dict())
    db.add(environment)
    db.commit()
    db.refresh(environment)
    
    return environment


@router.put("/{env_id}", response_model=EnvironmentSchema)
async def update_environment(
    env_id: int,
    env_in: EnvironmentUpdate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
) -> Any:
    """更新环境"""
    environment = db.query(Environment).filter(Environment.id == env_id).first()
    if not environment:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="环境不存在"
        )
    
    # 更新环境信息
    update_data = env_in.dict(exclude_unset=True)
    for field, value in update_data.items():
        setattr(environment, field, value)
    
    db.commit()
    db.refresh(environment)
    
    return environment


@router.delete("/{env_id}")
async def delete_environment(
    env_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
) -> Any:
    """删除环境"""
    environment = db.query(Environment).filter(Environment.id == env_id).first()
    if not environment:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="环境不存在"
        )
    
    # 软删除（禁用环境）
    environment.is_active = False
    db.commit()
    
    return {"message": "环境已删除"}


@router.get("/{env_id}/status")
async def get_environment_status(
    env_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
) -> Any:
    """获取环境状态"""
    environment = db.query(Environment).filter(Environment.id == env_id).first()
    if not environment:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="环境不存在"
        )
    
    # TODO: 实现环境状态检查逻辑
    return {
        "environment": environment.name,
        "status": "healthy",
        "resources": {
            "cpu": "80%",
            "memory": "60%",
            "disk": "40%"
        }
    }
